package com.cloudkinto.service.regular.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.bo.order.outbound.NormalOrderOutboundSaveBo;
import com.cloudkinto.common.BeanConvert;
import com.cloudkinto.common.RabbitQueueConstant;
import com.cloudkinto.common.RedisKeyConstants;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.OkHttpUtils;
import com.cloudkinto.common.utils.RakutenUtil;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.CompanyDao;
import com.cloudkinto.dao.PlatformOrderProductDao;
import com.cloudkinto.dao.PlatformOrderRegularDao;
import com.cloudkinto.dao.ProductDao;
import com.cloudkinto.dto.product.ProductMinSizeDto;
import com.cloudkinto.entity.*;
import com.cloudkinto.enumType.operate.OperateTypeEnum;
import com.cloudkinto.enumType.order.outbound.NormalOutboundStatusEnum;
import com.cloudkinto.enumType.order.outbound.OutboundOriginEnum;
import com.cloudkinto.enumType.order.outbound.SalesPlatformEnum;
import com.cloudkinto.service.event.order.OrderSubcontractEvent;
import com.cloudkinto.service.order.outbound.OutboundService;
import com.cloudkinto.service.platform.PlatformOrderPackageDetailService;
import com.cloudkinto.service.platform.PlatformOrderService;
import com.cloudkinto.service.platform.PlatformStoreService;
import com.cloudkinto.service.product.ProductService;
import com.cloudkinto.service.product.vo.ProductMsgVo;
import com.cloudkinto.service.regular.PlatformOrderRegularInfoService;
import com.cloudkinto.service.regular.PlatformOrderRegularService;
import com.cloudkinto.service.regular.PlatformOrderSplitRegularInfoService;
import com.cloudkinto.service.regular.PlatformOrderSplitRegularService;
import com.cloudkinto.service.regular.vo.OrderPackageRes;
import com.cloudkinto.service.regular.vo.PlatformOrderCheckReq;
import com.cloudkinto.service.regular.vo.ProductMemoMsg;
import com.cloudkinto.service.stock.ProductStockService;
import com.cloudkinto.service.warehouse.WarehouseService;
import com.cloudkinto.service.wr.QuotationSchemeService;
import com.cloudkinto.utils.BeanCopierUtils;
import com.cloudkinto.vo.product.ProductSkuVo;
import com.cloudkinto.vo.regular.*;
import com.cloudkinto.vo.regular.split.PlatSplitRegularPageDto;
import com.cloudkinto.vo.warehouse.CompanyWarehouseVo;
import com.cloudkinto.vo.wr.trial.LcCodeRes;
import com.cloudkinto.vo.wr.trial.TrialFreightRes;
import com.cloudkinto.vo.wr.trial.TrialOmsReq;
import com.cloudkinto.vo.wr.trial.TrialProductReq;
import lombok.RequiredArgsConstructor;
import okhttp3.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.cloudkinto.common.utils.OkHttpUtils.getUnsafeOkHttpClient;
import static com.cloudkinto.common.utils.RakutenUtil.createSPHeader;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author hua
 * @since 2024-11-28
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)//事务回滚
public class PlatformOrderRegularServiceImpl extends ServiceImpl<PlatformOrderRegularDao, PlatformOrderRegularDo> implements PlatformOrderRegularService {
    private final PlatformOrderRegularDao dao;
    private final PlatformOrderRegularInfoService platformOrderRegularInfoService;
    private final PlatformOrderSplitRegularService platformOrderSplitRegularService;
    private final PlatformOrderSplitRegularInfoService platformOrderSplitRegularInfoService;
    private final CompanyDao companyDao;
    private final PlatformStoreService platformStoreService;
    private final ProductDao productDao;
    private final ProductService productService;
    private final PlatformOrderService platformOrderService;
    private final QuotationSchemeService quotationSchemeService;
    private final RedisTemplate redisTemplate;
    private final OutboundService outboundService;
    private final PlatformOrderProductDao platformOrderProductDao;
    private final WarehouseService warehouseService;
    private final ProductStockService productStockService;
    private final PlatformOrderPackageDetailService platformOrderPackageDetailService;
    private final ApplicationContext context;
    private final RabbitTemplate rabbitTemplate;

    public void check(String regularName, Long id, Long companyId) {
        if (StringUtils.isBlank(regularName)) throw new BizException(SysConstant.Add_Name_Empty);
        //名称不能重复
        PlatformOrderRegularDo et = dao.selectOne(new LambdaQueryWrapper<PlatformOrderRegularDo>()
                .ne(id != null, PlatformOrderRegularDo::getId, id)
                .eq(PlatformOrderRegularDo::getRegularName, regularName)
                .eq(PlatformOrderRegularDo::getCompanyId, companyId));
        if (et != null) throw new BizException(SysConstant.Add_Name_Same);
    }

    @Override
    public Object add(PlatRegularAddReq req, Long userId, Long companyId) {
        CompanyDo companyDo = companyDao.selectById(companyId);
        if (companyDo == null) return null;
        this.check(req.getRegularName(), null, companyId);
        PlatformOrderRegularDo entityDo = new PlatformOrderRegularDo();
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setCompanyId(companyId);
        entityDo.setTenantId(companyDo.getTenantId());
        dao.insert(entityDo);
        entityDo.setSort(entityDo.getId());
        dao.updateById(entityDo);
        this.insertRuleInfos(req.getList(), entityDo.getId());
        return entityDo.getId();
    }

    public void insertRuleInfos(List<PlatRegularInfoAddReq> list, Long id) {
        List<PlatformOrderRegularInfoDo> regularInfoDos = BeanConvert.INSTANCE.platformOrderRegularInfoDo(list);
        for (int i = 0; i < regularInfoDos.size(); i++) {
            PlatformOrderRegularInfoDo regularInfoDo = regularInfoDos.get(i);
            if (StaticDict.Regular_ChildType.Four.getValue().equals(regularInfoDo.getChildType()) && StringUtils.isBlank(regularInfoDo.getStartValue())) {
                regularInfoDos.remove(i);
                i--;
                continue;
            }
            if (StringUtils.isBlank(regularInfoDo.getStartValue()) && StringUtils.isBlank(regularInfoDo.getEndValue())) {
                regularInfoDos.remove(i);
                i--;
                continue;
            }
            regularInfoDo.setRuleId(id);
        }
        platformOrderRegularInfoService.insertBatchMy(regularInfoDos);
    }

    @Override
    public Object update(PlatRegularUpdateReq req, Long userId, Long companyId) {
        this.check(req.getRegularName(), req.getId(), companyId);
        PlatformOrderRegularDo entityDo = dao.selectById(req.getId());
        if (entityDo == null || !Objects.equals(companyId, entityDo.getCompanyId())) return null;
        BeanUtils.copyProperties(req, entityDo);
        dao.updateById(entityDo);
        platformOrderRegularInfoService.lambdaUpdate().eq(PlatformOrderRegularInfoDo::getRuleId, entityDo.getId())
                .set(PlatformOrderRegularInfoDo::getDeleteBy, userId)
                .set(PlatformOrderRegularInfoDo::getDeleteTime, new Date())
                .set(PlatformOrderRegularInfoDo::getDeleteFlag, 1).update();
        this.insertRuleInfos(req.getList(), entityDo.getId());
        return entityDo.getId();
    }

    @Override
    public int delete(List<Long> ids, Long userId, Long companyId) {
        if (ids == null || ids.isEmpty()) return 0;
        boolean update = this.lambdaUpdate().in(PlatformOrderRegularDo::getId, ids).eq(PlatformOrderRegularDo::getCompanyId, companyId)
                .set(PlatformOrderRegularDo::getDeleteBy, userId)
                .set(PlatformOrderRegularDo::getDeleteTime, new Date())
                .set(PlatformOrderRegularDo::getDeleteFlag, 1).update();

        platformOrderRegularInfoService.lambdaUpdate().in(PlatformOrderRegularInfoDo::getRuleId, ids)
                .set(PlatformOrderRegularInfoDo::getDeleteBy, userId)
                .set(PlatformOrderRegularInfoDo::getDeleteTime, new Date())
                .set(PlatformOrderRegularInfoDo::getDeleteFlag, 1).update();
        return update ? 1 : 0;
    }


    @Override
    public PlatRegularUpdateReq detail(Long id) {
        PlatformOrderRegularDo entityDo = dao.selectById(id);
        PlatRegularUpdateReq res = new PlatRegularUpdateReq();
        BeanUtils.copyProperties(entityDo, res);
        List<PlatformOrderRegularInfoDo> regularInfoDos = platformOrderRegularInfoService.lambdaQuery().eq(PlatformOrderRegularInfoDo::getRuleId, id).list();
        List<PlatRegularInfoAddReq> list = BeanCopierUtils.listCopyMapper(regularInfoDos, PlatformOrderRegularInfoDo.class, PlatRegularInfoAddReq.class);
        res.setList(list);
        List<String> productIds = regularInfoDos.stream().filter(i -> StaticDict.Regular_ChildType.Five.getValue().equals(i.getChildType()))
                .map(PlatformOrderRegularInfoDo::getStartValue).collect(Collectors.toList());
        if (!productIds.isEmpty()) {
            List<ProductDo> productDos = productDao.selectBatchIds(productIds);
            List<ProductSkuVo> products = BeanCopierUtils.listCopyMapper(productDos, ProductDo.class, ProductSkuVo.class);
            res.setProducts(products);
        }
        return res;
    }

    @Override
    public SingleResult pageInit(Long companyId) {
        Map<String, Object> map = new HashMap<>();
        map.put("moduleTypeList", StaticDict.getRegular_ModuleType());
        map.put("childTypeList", StaticDict.getRegular_ChildType());
        map.put("storeList", platformStoreService.getList(companyId));
        map.put("platformCode", StaticDict.getStore_PlatformCode());
        return SingleResult.success(map);
    }

    @Override
    public List<PlatRegularPageDto> getList(Map<String, Object> map) {
        List<PlatRegularPageDto> resList = dao.listPage(map);
        return resList;
    }

    @Override
    public PageResult getListPage(Map<String, Object> map) {
        IPage<PlatRegularPageDto> page = pageInit(map);
        page = dao.listPage(page, map);
        PageResult result = new PageResult(page.getRecords(), (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    private IPage<PlatRegularPageDto> pageInit(Map<String, Object> map) {
        IPage<PlatRegularPageDto> page = new Page<>();
        page.setSize(map.get("pageSize") != null ? Long.parseLong(map.get("pageSize").toString()) : 10);
        page.setCurrent(map.get("current") != null ? Long.parseLong(map.get("current").toString()) : 1);
        return page;
    }

    private QueryWrapper<PlatformOrderRegularDo> queryBuild(Map<String, String> map) {
        QueryWrapper<PlatformOrderRegularDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("regularName"))) {
            wrapper.like("regular_name", map.get("regularName"));
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", map.get("status"));
        }
        wrapper.eq("company_id", map.get("companyId"));

        wrapper.orderByDesc("sort");
        return wrapper;
    }


    //更新排序
    @Override
    public void updateSort(PlatRegularSortReq req, Long userId, Long companyId) {
        List<Long> ids = req.getIds();
        if (ids == null || ids.isEmpty()) return;
        List<PlatformOrderRegularDo> list = this.lambdaQuery().eq(PlatformOrderRegularDo::getCompanyId, companyId)
                .in(PlatformOrderRegularDo::getId, ids).list();
        Map<Long, Long> collect = list.stream().collect(Collectors.toMap(PlatformOrderRegularDo::getId, PlatformOrderRegularDo::getSort));

        List<Long> values = new ArrayList<>(collect.values());
        values.sort(Collections.reverseOrder());
        if (ids.size() != values.size()) return;
        for (int i = 0; i < ids.size(); i++) {
            this.lambdaUpdate().eq(PlatformOrderRegularDo::getId, ids.get(i))
                    .set(PlatformOrderRegularDo::getUpdateBy, userId)
                    .set(PlatformOrderRegularDo::getUpdateTime, new Date())
                    .set(PlatformOrderRegularDo::getSort, values.get(i)).update();
        }
    }

    @Override
    public void updateRegularStatus(PlatRegularStatusReq req, Long userId, Long companyId) {
        List<Long> ids = req.getIds();
        if (ids == null || ids.isEmpty()) return;
        this.lambdaUpdate().in(PlatformOrderRegularDo::getId, ids)
                .eq(PlatformOrderRegularDo::getCompanyId, companyId)
                .ne(PlatformOrderRegularDo::getStatus, req.getStatus())
                .set(PlatformOrderRegularDo::getUpdateBy, userId)
                .set(PlatformOrderRegularDo::getUpdateTime, new Date())
                .set(PlatformOrderRegularDo::getStatus, req.getStatus()).update();
    }



    //给平台订单分配物流渠道和仓库
    @Override
    public void orderRule(PlatformOrderCheckReq req) {
        Long sendWhId = req.getOrderDo().getSendWhId();
        Long sendChannelId = req.getOrderDo().getChannelId();
        Integer reserveFlag = req.getOrderDo().getReserveFlag();
        PlatformOrderDo orderDo = platformOrderService.getById(req.getOrderDo().getId());
        if (orderDo == null || !StaticDict.Platform_Order_Status.Zero.getValue().equals(orderDo.getStatus())) {
            return;
        }
        if (StaticDict.Store_PlatformCode.Amazon.getValue().equals(orderDo.getPlatformCode()) && StringUtils.isBlank(orderDo.getPostcode())) {
            this.updateAuditCause(req.isMergeFlag() ? req.getOrderIds() : Arrays.asList(orderDo.getId()), req.isMergeFlag(), StaticDict.PlatformOrder_Audit_Code.AFN_Order.getValue(), "AFN订单");
            return;
        }
        if (StringUtils.isNotBlank(req.getMergeOrderNo())) {
            orderDo.setPlatformOrderNo(req.getMergeOrderNo());
        }
        orderDo.setSendWhId(sendWhId);
        orderDo.setChannelId(sendChannelId);
        orderDo.setReserveFlag(reserveFlag);
        //是否是预约单 2025-04-22 暂时去掉预约单的判断
//        Date now = new Date();
//        if (orderDo.getReserveFlag() == 1 && orderDo.getReserveBeginTime() != null && now.before(orderDo.getReserveBeginTime())) {
//            //预约单子  如果现在时间小于 预约开始时间 就不分配
//            this.updateAuditCause(req.isMergeFlag() ? req.getOrderIds() : Arrays.asList(orderDo.getId()), req.isMergeFlag(),"预约单未到时间:" + DateUtils.dateFormatToString(orderDo.getReserveBeginTime()), null);
//            return;
//        }
        if (req.getProductDos() == null || req.getProductDos().isEmpty()) {
            this.updateAuditCause(req.isMergeFlag() ? req.getOrderIds() : Arrays.asList(orderDo.getId()), req.isMergeFlag(), StaticDict.PlatformOrder_Audit_Code.PlatformSku_NUll.getValue(), "无平台sku");
            return;
        }
        if (req.isNeedMatchSku()) {
            List<PlatformOrderProductDo> toMatch = req.getProductDos().stream().filter(i -> i.getSkuType() == 1 && i.getProductId() == null).collect(Collectors.toList());
            List<PlatformOrderProductDo> matchedList = req.getProductDos().stream().filter(i -> !(i.getSkuType() == 1 && i.getProductId() == null)).collect(Collectors.toList());
            platformOrderService.matchSystemSku(toMatch, orderDo.getStoreId(), req.getCompanyId(), req.getTenantId());
            for (PlatformOrderProductDo productDo : toMatch) {
                if (productDo.getProductId() == null) {
                    continue;
                }
                if (productDo.getId() == null) {
                    platformOrderProductDao.insert(productDo);
                }
                else {
                    platformOrderProductDao.updateById(productDo);
                }
            }
            if (!toMatch.isEmpty()) {
                matchedList.addAll(toMatch);
                Map<Long, List<PlatformOrderProductDo>> productOrderMap = matchedList.stream().collect(Collectors.groupingBy(PlatformOrderProductDo::getOrderId));
                for (Long orderId : productOrderMap.keySet()) {
                    StringBuilder mergeOrderSku = new StringBuilder();
                    for (PlatformOrderProductDo productDo : productOrderMap.get(orderId)) {
                        if (productDo.getProductId() == null || StringUtils.isBlank(productDo.getSku())) {
                            continue;
                        }
                        if (StringUtils.isNotBlank(mergeOrderSku.toString())) {
                            mergeOrderSku.append(";");
                        }
                        mergeOrderSku.append(productDo.getSku()).append("*").append(productDo.getQty());
                    }
                    if (mergeOrderSku.length() > 100) {
                        mergeOrderSku.delete(100, mergeOrderSku.length());
                    }
                    if (StringUtils.isNotBlank(mergeOrderSku.toString())) {
                        LambdaUpdateWrapper<PlatformOrderDo> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.eq(PlatformOrderDo::getId, orderId);
                        updateWrapper.set(PlatformOrderDo::getSku, mergeOrderSku.toString());
                        platformOrderService.update(updateWrapper);
                    }
                }
            }
            req.setProductDos(matchedList);
        }
        boolean platSkuMatch = true;//平台sku是否全部匹配
        for (PlatformOrderProductDo productDo : req.getProductDos()) {
            if (StringUtils.isBlank(productDo.getSku()) || productDo.getProductId() == null) {
                platSkuMatch = false;
                break;
            }
        }
        if (!platSkuMatch) {
            this.updateAuditCause(req.isMergeFlag() ? req.getOrderIds() : Arrays.asList(orderDo.getId()), req.isMergeFlag(), StaticDict.PlatformOrder_Audit_Code.Sku_NotMatch.getValue(),"平台sku未匹配");
            return;
        }
        //平台订单拆分规则
        Map<String, Object> map = new HashMap<>();
        map.put("status", "0");
        map.put("companyId", req.getCompanyId());
        map.put("splitType", "0");
        List<PlatSplitRegularPageDto> splitRegularDoList = new ArrayList<>();
        if ((req.getProductDos().size() <= 1 && req.getProductDos().get(0).getQty() == 1) || req.isMergeFlag()
                || StaticDict.Store_PlatformCode.Qoo10.getValue().equals(req.getOrderDo().getPlatformCode())) {
            splitRegularDoList = new ArrayList<>();
        }
        else {
            splitRegularDoList = platformOrderSplitRegularService.getList(map);
        }
        List<Long> regularIds = splitRegularDoList.stream().map(PlatSplitRegularPageDto::getId).collect(Collectors.toList());
        Map<Long, List<PlatformOrderSplitRegularInfoDo>> regularInfoMap = new HashMap<>();
        if (!regularIds.isEmpty()) {
            List<PlatformOrderSplitRegularInfoDo> regularInfoDos = platformOrderSplitRegularInfoService.lambdaQuery()
                    .in(PlatformOrderSplitRegularInfoDo::getRuleId, regularIds).list();
            regularInfoMap = regularInfoDos.stream().collect(Collectors.groupingBy(PlatformOrderSplitRegularInfoDo::getRuleId));
        }
        PlatSplitRegularPageDto splitRuleId = null;
        first:
        for (PlatSplitRegularPageDto splitRuleDto : splitRegularDoList) {
            List<PlatformOrderSplitRegularInfoDo> regularInfoDos = regularInfoMap.get(splitRuleDto.getId());
            if (regularInfoDos == null || regularInfoDos.isEmpty()) {
                continue;
            }
            //过滤掉设置定动作
            Map<Integer, List<PlatformOrderSplitRegularInfoDo>> regularChildMap = regularInfoDos.stream()
                    .filter(i -> !StaticDict.Regular_Split_ModuleType.Zero.getValue().equals(i.getModuleType()))
                    .collect(Collectors.groupingBy(PlatformOrderSplitRegularInfoDo::getChildType));
            for (Integer childType : regularChildMap.keySet()) {
                List<PlatformOrderSplitRegularInfoDo> splitChildList = regularChildMap.get(childType);
                if (StaticDict.Regular_Split_ChildType.Five.getValue().equals(childType)) {
                    //订单产品
                    List<String> values = splitChildList.stream().map(PlatformOrderSplitRegularInfoDo::getStartValue).collect(Collectors.toList());
                    if (0 == splitChildList.get(0).getChildMode()) {
                        //全部产品包含在指定产品范围内
                        for (PlatformOrderProductDo productDo : req.getProductDos()) {
                            if (!values.contains(productDo.getProductId()+"")) {
                                continue first;
                            }
                        }
                    }
                    else if (1 == splitChildList.get(0).getChildMode()) {
                        //全部产品不包含在指定产品范围内
                        for (PlatformOrderProductDo productDo : req.getProductDos()) {
                            if (values.contains(productDo.getProductId()+"")) {
                                continue first;
                            }
                        }
                    }
                    else if (2 == splitChildList.get(0).getChildMode()) {
                        //任一产品在指定产品范围内
                        boolean flag = false;
                        for (PlatformOrderProductDo productDo : req.getProductDos()) {
                            if (values.contains(productDo.getProductId()+"")) {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag) {
                            continue first;
                        }
                    }
                    else if (3 == splitChildList.get(0).getChildMode()) {
                        //任一产品不在指定产品范围内
                        boolean flag = false;
                        for (PlatformOrderProductDo productDo : req.getProductDos()) {
                            if (values.contains(productDo.getProductId()+"")) {
                                flag = true;
                                break;
                            }
                        }
                        if (flag) {
                            continue first;
                        }
                    }
                }
                else if (StaticDict.Regular_Split_ChildType.Six.getValue().equals(childType)) {
                    //产品数量
                    if (0 == splitChildList.get(0).getChildMode()) {
                        //总产品数量
                        int sum = req.getProductDos().stream().mapToInt(PlatformOrderProductDo::getQty).sum();
                        for (PlatformOrderSplitRegularInfoDo splitInfoDo : splitChildList) {
                            if (splitInfoDo.getStartMatchType() != null && StringUtils.isNotBlank(splitInfoDo.getStartValue())) {
                                if (splitInfoDo.getStartMatchType() == 5) {
                                    //大于等于
                                    if (sum < Integer.parseInt(splitInfoDo.getStartValue())) {
                                        continue first;
                                    }
                                }
                                else if (splitInfoDo.getStartMatchType() == 4) {
                                    if (sum <= Integer.parseInt(splitInfoDo.getStartValue())) {
                                        continue first;
                                    }
                                }
                            }
                            else if (splitInfoDo.getEndMatchType() != null && StringUtils.isNotBlank(splitInfoDo.getEndValue())) {
                                if (splitInfoDo.getEndMatchType() == 6) {
                                    //小雨
                                    if (sum >= Integer.parseInt(splitInfoDo.getEndValue())) {
                                        continue first;
                                    }
                                }
                                else if (splitInfoDo.getEndMatchType() == 7) {
                                    //小于等于
                                    if (sum > Integer.parseInt(splitInfoDo.getEndValue())) {
                                        continue first;
                                    }
                                }
                            }
                        }
                    }
                    else if (1 == splitChildList.get(0).getChildMode()) {
                        //sku数量
                        Map<Long, Integer> collect = req.getProductDos().stream().collect(Collectors.groupingBy(PlatformOrderProductDo::getProductId, Collectors.summingInt(PlatformOrderProductDo::getQty)));
                        Integer startMode = splitChildList.get(splitChildList.size() -1).getStartMatchType();
                        if (8 == startMode) {
                            //并且
                            for (PlatformOrderSplitRegularInfoDo splitInfoDo : splitChildList) {
                                Long productId = Long.parseLong(splitInfoDo.getStartValue());
                                if (collect.get(productId) == null) {
                                    continue first;
                                }
                                Integer qty = collect.get(productId);
                                if (splitInfoDo.getEndMatchType() != null && StringUtils.isNotBlank(splitInfoDo.getEndValue())) {
                                    if (splitInfoDo.getEndMatchType() == 1) {
                                        //等于
                                        if (!(qty+"").equals(splitInfoDo.getEndValue())) {
                                            continue first;
                                        }
                                    }
                                    else if (splitInfoDo.getEndMatchType() == 4) {
                                        //大于
                                        if (qty <= Integer.parseInt(splitInfoDo.getEndValue())) {
                                            continue first;
                                        }
                                    }
                                    else if (splitInfoDo.getEndMatchType() == 6) {
                                        //小于
                                        if (qty >= Integer.parseInt(splitInfoDo.getEndValue())) {
                                            continue first;
                                        }
                                    }
                                    else if (splitInfoDo.getEndMatchType() == 7) {
                                        //小于等于
                                        if (qty > Integer.parseInt(splitInfoDo.getEndValue())) {
                                            continue first;
                                        }
                                    }
                                    else if (splitInfoDo.getEndMatchType() == 5) {
                                        //大于等于
                                        if (qty < Integer.parseInt(splitInfoDo.getEndValue())) {
                                            continue first;
                                        }
                                    }
                                    else if (splitInfoDo.getEndMatchType() == 9) {
                                        //不等于
                                        if ((qty+"").equals(splitInfoDo.getEndValue())) {
                                            continue first;
                                        }
                                    }
                                }
                            }
                        }
                        else if (10 == startMode) {
                            //或者
                            boolean flag = false;
                            for (PlatformOrderSplitRegularInfoDo splitInfoDo : splitChildList) {
                                Long productId = Long.parseLong(splitInfoDo.getStartValue());
                                if (collect.get(productId) == null) {
                                    continue first;
                                }
                                Integer qty = collect.get(productId);
                                if (splitInfoDo.getEndMatchType() != null && StringUtils.isNotBlank(splitInfoDo.getEndValue())) {
                                    if (splitInfoDo.getEndMatchType() == 1) {
                                        //等于
                                        if ((qty+"").equals(splitInfoDo.getEndValue())) {
                                            flag = true;
                                            break;
                                        }
                                    }
                                    else if (splitInfoDo.getEndMatchType() == 4) {
                                        //大于
                                        if (qty > Integer.parseInt(splitInfoDo.getEndValue())) {
                                            flag = true;
                                            break;
                                        }
                                    }
                                    else if (splitInfoDo.getEndMatchType() == 6) {
                                        //小于
                                        if (qty < Integer.parseInt(splitInfoDo.getEndValue())) {
                                            flag = true;
                                            break;
                                        }
                                    }
                                    else if (splitInfoDo.getEndMatchType() == 7) {
                                        //小于等于
                                        if (qty <= Integer.parseInt(splitInfoDo.getEndValue())) {
                                            flag = true;
                                            break;
                                        }
                                    }
                                    else if (splitInfoDo.getEndMatchType() == 5) {
                                        //大于等于
                                        if (qty >= Integer.parseInt(splitInfoDo.getEndValue())) {
                                            flag = true;
                                            break;
                                        }
                                    }
                                    else if (splitInfoDo.getEndMatchType() == 9) {
                                        //不等于
                                        if (!(qty+"").equals(splitInfoDo.getEndValue())) {
                                            flag = true;
                                            break;
                                        }
                                    }
                                }
                            }
                            if (!flag) {
                                continue first;
                            }
                        }
                    }
                }
            }

            splitRuleId = splitRuleDto;
            break first;
        }
        List<PlatformOrderCheckReq> splitCheckList = new ArrayList<>();
        if (splitRuleId != null) {
            //拆分订单
            List<String> splitMode = regularInfoMap.get(splitRuleId.getId()).stream()
                    .filter(i -> StaticDict.Regular_Split_ModuleType.Zero.getValue().equals(i.getModuleType())
                            && StaticDict.Regular_Split_ChildType.Eleventh.getValue().equals(i.getChildType())).map(PlatformOrderSplitRegularInfoDo::getStartValue).collect(Collectors.toList());
            //执行动作 目前 就 按产品拆分
            if (!splitMode.isEmpty()) {
                if ("0".equals(splitMode.get(0))) {
                    //相同产品拆为一单 todo 按照sku 合并一下 合并订单 可能有相同sku
                    Map<String, List<PlatformOrderProductDo>> collect = req.getProductDos().stream().collect(Collectors.groupingBy(i -> i.getSku()));
                    for (String sku : collect.keySet()) {
                        PlatformOrderProductDo platformProductDo = new PlatformOrderProductDo();
                        BeanUtils.copyProperties(collect.get(sku).get(0), platformProductDo);
                        platformProductDo.setQty(collect.get(sku).stream().mapToInt(PlatformOrderProductDo::getQty).sum());
                        PlatformOrderCheckReq platformOrderCheckReq = new PlatformOrderCheckReq(req.getOrderDo(), Arrays.asList(platformProductDo));
                        splitCheckList.add(platformOrderCheckReq);
                    }

                    for (PlatformOrderProductDo productDo : req.getProductDos()) {
                        splitCheckList.add(new PlatformOrderCheckReq(req.getOrderDo(), Arrays.asList(productDo)));
                    }
                }
                else if ("1".equals(splitMode.get(0))) {
                    //每件产品拆为一单
                    for (PlatformOrderProductDo productDo : req.getProductDos()) {
                        for (int i = 0; i < productDo.getQty(); i++) {
                            PlatformOrderProductDo splitProductDo = new PlatformOrderProductDo(productDo.getOrderId(), productDo.getPlatformOrderNo(),
                                    productDo.getPlatformParentSku(), productDo.getPlatformSku(), productDo.getPlatformQty(), productDo.getProductId(),
                                    productDo.getSku(), 1, productDo.getSkuType(), productDo.getCurrencyCode());
                            splitCheckList.add(new PlatformOrderCheckReq(req.getOrderDo(), Arrays.asList(splitProductDo)));
                        }
                    }
                }
                else if ("2".equals(splitMode.get(0))) {
                    //所选产品拆为一单
                    List<String> splitProductIds = regularInfoMap.get(splitRuleId.getId()).stream().filter(i -> StaticDict.Regular_Split_ChildType.Twelfth.getValue().equals(i.getChildType()))
                            .map(PlatformOrderSplitRegularInfoDo::getStartValue).collect(Collectors.toList());
                    splitCheckList.add(new PlatformOrderCheckReq(req.getOrderDo(), req.getProductDos().stream().filter(i -> splitProductIds.contains(i.getProductId()+"")).collect(Collectors.toList())));
                    splitCheckList.add(new PlatformOrderCheckReq(req.getOrderDo(), req.getProductDos().stream().filter(i -> !splitProductIds.contains(i.getProductId()+"")).collect(Collectors.toList())));
                }
            }
        }
        boolean splitFlag = !splitCheckList.isEmpty();
        if (splitCheckList.isEmpty()) {
            splitCheckList.add(new PlatformOrderCheckReq(req.getOrderDo(), req.getProductDos()));
        }
        List<NormalOrderOutboundSaveBo> saveBos = new ArrayList<>();
        List<List<PlatformOrderPackageDetailDo>> packageListList = new ArrayList<>();
        for (PlatformOrderCheckReq orderCheckReq : splitCheckList) {
            List<TrialFreightRes> freightResList = new ArrayList<>();
            String error = this.getTrackId(orderCheckReq.getOrderDo(), orderCheckReq.getProductDos(), freightResList);
            if (freightResList.isEmpty() || freightResList.get(0).getWhId() == null || freightResList.get(0).getChannelId() == null) {
                if (splitFlag) {
                    //说明拆分订单没有 匹配到物流渠道
                    error = "拆分订单后("+ splitRuleId.getRegularName() +"), " + error;
                }
                String auditCode = StaticDict.PlatformOrder_Audit_Code.GetTrackId_Error.getValue();
                if (error.contains("库存不足")) {
                    auditCode = StaticDict.PlatformOrder_Audit_Code.Stock_NotEnough.getValue();
                }
                this.updateAuditCause(req.isMergeFlag() ? req.getOrderIds() : Arrays.asList(orderDo.getId()), req.isMergeFlag(), auditCode, error);
                return;
            }
            //排序
            freightResList.sort(new Comparator<TrialFreightRes>() {
                @Override
                public int compare(TrialFreightRes o1, TrialFreightRes o2) {
                    return Double.compare(o1.getLogBaseFee() + o1.getSurchargeFee(), o2.getLogBaseFee() + o2.getSurchargeFee());
                }
            });
            NormalOrderOutboundSaveBo saveBo = new NormalOrderOutboundSaveBo();
            saveBo.setStatus(NormalOutboundStatusEnum.one.getValue());
            saveBo.setWhId(freightResList.get(0).getWhId());
            saveBo.setLogisticsChannelId(freightResList.get(0).getChannelId());
            saveBo.setCarrier(freightResList.get(0).getCarrier());
//            List<Long> openStoreIds =  Arrays.asList(5L, 17L, 18L, 24L, 6L, 8L, 1L, 19L);
            List<Long> range = platformOrderService.getAutoCheckStoreList(orderDo.getCompanyId());
            if (freightResList.get(0).getWarehouseType() == 1 && "DL01".equals(freightResList.get(0).getWarehouseCode()) && range.contains(orderDo.getStoreId())) {//目前只开放 乐天6号店
                saveBo.setSendOut(1);
            }
            else {
                saveBo.setSendOut(0);
            }
            saveBo.setTrackingNumber(orderDo.getTrackNo());
            saveBo.setSalesPlatform(SalesPlatformEnum.getCodeByPlatCode(orderDo.getPlatformCode()));
            saveBo.setStoreId(orderDo.getStoreId());
            saveBo.setPlatformOrderNo(orderDo.getPlatformOrderNo());
            saveBo.setRemark(orderDo.getRemark());
            saveBo.setTotalNum(orderCheckReq.getProductDos().stream().mapToInt(PlatformOrderProductDo::getQty).sum());
            saveBo.setReceiver(orderDo.getReceiver());
            saveBo.setPhone(orderDo.getTelephone());
            saveBo.setEmail(orderDo.getBuyerEmail());
            saveBo.setCountryRegionCode(orderDo.getCountryRegionCode());
            saveBo.setProvinceName(orderDo.getDistrict());
            saveBo.setCityName(orderDo.getCityCode());
            saveBo.setPostCode(orderDo.getPostcode());
            saveBo.setHouseNum(orderDo.getHouseNum());
            saveBo.setAddress1(orderDo.getAddressOne());
            StringBuilder addressTwo = new StringBuilder();
            if (StringUtils.isNotBlank(orderDo.getAddressTwo())) {
                addressTwo.append(orderDo.getAddressTwo());
            }
            if (StringUtils.isNotBlank(orderDo.getAddressTri())) {
                addressTwo.append(orderDo.getAddressTri());
            }
            saveBo.setAddress2(addressTwo.toString());
            saveBo.setReserveFlag(orderDo.getReserveFlag());
            saveBo.setReserveBeginTime(orderDo.getReserveBeginTime());
            saveBo.setReserveEndTime(orderDo.getReserveEndTime());
            saveBo.setDeliveryDate(orderDo.getDeliveryDate());
            saveBo.setDeliveryTimeName(orderDo.getDeliveryTimeName());
            saveBo.setInsuranceFlag(false);
            //产品
            List<NormalOrderOutboundSaveBo.NormalOrderOutboundProductSaveBo> productInfoList = new ArrayList<>();
            for (PlatformOrderProductDo orderProductDo : orderCheckReq.getProductDos()) {
                productInfoList.add(new NormalOrderOutboundSaveBo.NormalOrderOutboundProductSaveBo(orderProductDo.getProductId(), orderProductDo.getSku(), orderProductDo.getQty(), null, null));
            }
            saveBo.setProductInfoList(productInfoList);
            saveBos.add(saveBo);
            List<List<ProductMemoMsg>> packageList = new ArrayList<>();
            if (saveBo.getLogisticsChannelId() != 3) {//todo 根据后续要求要改
                //黑猫宅急便
                OrderPackageRes packageRes = this.getPackageList(orderCheckReq.getProductDos());
                packageList = packageRes.getPackageList();
            }
            List<PlatformOrderPackageDetailDo> oneOrderPackDetailDoList = platformOrderPackageDetailService.getOneOrderPackDetailDoList(packageList, orderDo.getId(), orderDo.getPlatformOrderNo(), null, req.getUserId());
            packageListList.add(oneOrderPackDetailDoList);
        }
        //下单成功
        this.updatePlatOrderSuccess(req.isMergeFlag() ? req.getOrderIds() : Arrays.asList(orderDo.getId()), saveBos.get(0).getWhId(), saveBos.get(0).getLogisticsChannelId(), saveBos.get(0).getCarrier(), req.getUserId());
        //如果自动提交仓库 todo 判断是否自动
        Object autoSubmit = redisTemplate.opsForValue().get(RedisKeyConstants.Oms_PlatformOrder_AutoSubmit_ + req.getCompanyId());
        if (!Objects.equals(autoSubmit, 1)) {
            System.out.println("平台订单设置不自动提交仓库");
            return;
        }
        //掉创建一见代发出库接口。推送 如果推送成功则改为 处理中 状态， 如果推送失败 将失败原因填充上来
        boolean savaFlag = true;
        List<Long> outIds = new ArrayList<>();
        for (NormalOrderOutboundSaveBo saveBo : saveBos) {
            try {
                Long outId = outboundService.normalSave(saveBo, req.getUserId(), "system", req.getCompanyId(), req.getTenantId(), OutboundOriginEnum.three);
                outIds.add(outId);
            } catch (Exception e) {
                savaFlag = false;
                e.printStackTrace();
                break;
            }
        }
        if (!savaFlag) {
            //推送到wms 异常
            for (Long outId : outIds) {
                outboundService.delete(outId, req.getUserId());
            }
        }
        LambdaUpdateWrapper<PlatformOrderDo> updateWrapper = new LambdaUpdateWrapper<PlatformOrderDo>();
        updateWrapper.in(PlatformOrderDo::getId, req.isMergeFlag() ? req.getOrderIds() : Arrays.asList(orderDo.getId()));
        if (savaFlag) {
            updateWrapper.set(PlatformOrderDo::getStatus, StaticDict.Platform_Order_Status.Two.getValue());
            updateWrapper.set(PlatformOrderDo::getDistributeBy, req.getUserId());
            updateWrapper.set(PlatformOrderDo::getDistributeTime, new Date());
            updateWrapper.set(PlatformOrderDo::getAuditCode, null);
            updateWrapper.set(PlatformOrderDo::getAuditCause, null);
        }
        else {
            updateWrapper.set(PlatformOrderDo::getAuditCode, StaticDict.PlatformOrder_Audit_Code.PUSH_WMS_ERROR.getValue());
            updateWrapper.set(PlatformOrderDo::getAuditCause, "推送到wms异常");
            updateWrapper.set(PlatformOrderDo::getStatus, StaticDict.Platform_Order_Status.Five.getValue());
        }
        platformOrderService.update(updateWrapper);
        // 操作日志
        List<OperateRecordDo> operateRecordDos = new ArrayList<>();
        if (req.isMergeFlag()) {
            for (Long orderId : req.getOrderIds()) {
                OperateRecordDo operateRecordDo = new OperateRecordDo(orderId, OperateTypeEnum.PlatformOrder.getValue(),
                        savaFlag ? SysConstant.platformOrder_Check : SysConstant.platformOrder_CheckFail,
                        req.getUserId(), new Date(), savaFlag ? null : "推送到wms异常");
                operateRecordDos.add(operateRecordDo);
            }
        }
        else {
            OperateRecordDo operateRecordDo = new OperateRecordDo(orderDo.getId(), OperateTypeEnum.PlatformOrder.getValue(),
                    savaFlag ? SysConstant.platformOrder_Check : SysConstant.platformOrder_CheckFail,
                    req.getUserId(), new Date(), savaFlag ? null : "推送到wms异常");
            operateRecordDos.add(operateRecordDo);
        }
        if (savaFlag) {
            List<PlatformOrderPackageDetailDo> packageDetailDoList = new ArrayList<>();
            for (List<PlatformOrderPackageDetailDo> platformOrderPackageDetailDos : packageListList) {
                packageDetailDoList.addAll(platformOrderPackageDetailDos);
            }
            platformOrderPackageDetailService.insetBatchMy(packageDetailDoList);
            for (int i = 0; i < packageListList.size(); i++) {
                List<PlatformOrderPackageDetailDo> oneOrderPackDetailDoList = packageListList.get(i);
                //分包裹
                if (CollUtil.isNotEmpty(oneOrderPackDetailDoList)) {
                    //分包后置处理 如果交给异步去处理，会有一个问题，整点订单提交 但是包裹分包没有提交，导致京东那边获取的还是默认包裹
                    outboundService.dealPackageDetail(new OrderSubcontractEvent(orderDo.getPlatformOrderNo(), outIds.get(i), oneOrderPackDetailDoList));
//                    context.publishEvent(new OrderSubcontractEvent(orderDo.getPlatformOrderNo(), outIds.get(i), oneOrderPackDetailDoList));
                }
            }
        }
        if (!operateRecordDos.isEmpty()) {
            List<List<OperateRecordDo>> partition = ListUtil.partition(operateRecordDos, 3000);
            for (List<OperateRecordDo> partList : partition) {
                rabbitTemplate.convertAndSend(RabbitQueueConstant.CrossMall_CMOrder_OperateList, JSON.toJSONString(partList));
            }
        }
    }


    public String getTrackId(PlatformOrderDo orderDo, List<PlatformOrderProductDo> productDos, List<TrialFreightRes> freightResList) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", "0");
        map.put("companyId", orderDo.getCompanyId());
        List<PlatRegularPageDto> regularList = dao.listPage(map);
        List<Long> regularIds = regularList.stream().map(PlatRegularPageDto::getId).collect(Collectors.toList());
        Map<Long, List<PlatformOrderRegularInfoDo>> regularInfoMap = new HashMap<>();
        if (!regularIds.isEmpty()) {
            List<PlatformOrderRegularInfoDo> regularInfoDos = platformOrderRegularInfoService.lambdaQuery()
                    .in(PlatformOrderRegularInfoDo::getRuleId, regularIds).list();
            regularInfoMap = regularInfoDos.stream().collect(Collectors.groupingBy(PlatformOrderRegularInfoDo::getRuleId));
        }
        //库存够不够
        Map<Long, Integer> skuQtyMap = new HashMap<>();
        for (PlatformOrderProductDo productDo : productDos) {
            skuQtyMap.merge(productDo.getProductId(), productDo.getQty(), Integer::sum);
        }
        //记录仓库库存是否足够
        Map<Long, Boolean> whStockFlagMap = new HashMap<>();
        StringBuilder error = new StringBuilder();
        Long whId = null;
        Long channelId = null;
        String reglarName = "";
        if (orderDo.getSendWhId() == null) {//没有仓库 才走平台订单规则
            Long regularId = null;
            //先获取仓库
            first:
            for (PlatRegularPageDto regularDo : regularList) {
                //根据条件 判断符不符合该规则
                List<PlatformOrderRegularInfoDo> regularInfoDos = regularInfoMap.get(regularDo.getId());
                if (regularInfoDos == null || regularInfoDos.isEmpty()) {
                    continue;
                }
                if (regularDo.getRegularType() == 2) {
                    //应用于所有订单
                    regularId = regularDo.getId();
                    reglarName = regularDo.getRegularName();
                    break;
                }
                //过滤掉设置定动作
                Map<Integer, List<PlatformOrderRegularInfoDo>> regularChildMap = regularInfoDos.stream()
                        .filter(i -> !StaticDict.Regular_ModuleType.Zero.getValue().equals(i.getModuleType()))
                        .collect(Collectors.groupingBy(PlatformOrderRegularInfoDo::getChildType));
                for (Integer childType : regularChildMap.keySet()) {
                    List<PlatformOrderRegularInfoDo> childRegularInfoList = regularChildMap.get(childType);
                    if (StaticDict.Regular_ChildType.OrderPlat.getValue().equals(childType)) {
                        List<String> values = childRegularInfoList.stream().map(PlatformOrderRegularInfoDo::getStartValue).collect(Collectors.toList());
                        //订单平台
                        if (!values.contains(orderDo.getPlatformCode())) {
                            continue first;
                        }
                    } else if (StaticDict.Regular_ChildType.One.getValue().equals(childType)) {
                        //订单站点
                        List<String> values = childRegularInfoList.stream().map(PlatformOrderRegularInfoDo::getStartValue).collect(Collectors.toList());
                        if (!values.contains(orderDo.getPlatformCode())) {
                            continue first;
                        }
                    } else if (StaticDict.Regular_ChildType.Two.getValue().equals(childType)) {
                        //订单店铺
                        List<String> values = childRegularInfoList.stream().map(PlatformOrderRegularInfoDo::getStartValue).collect(Collectors.toList());
                        if (!values.contains(orderDo.getStoreId() + "")) {
                            continue first;
                        }
                    } else if (StaticDict.Regular_ChildType.Three.getValue().equals(childType)) {
                        //收货国家/地区
                        List<String> values = childRegularInfoList.stream().map(PlatformOrderRegularInfoDo::getStartValue).collect(Collectors.toList());
                        if (!values.contains(orderDo.getCountryRegionCode())) {
                            continue first;
                        }
                    } else if (StaticDict.Regular_ChildType.Four.getValue().equals(childType)) {
                        //收货邮编  开头
                        if (StringUtils.isBlank(orderDo.getPostcode())) {
                            continue first;
                        }
                        String postCode = orderDo.getPostcode().replaceAll("-", "");
                        List<String> values = childRegularInfoList.stream().map(PlatformOrderRegularInfoDo::getStartValue).filter(StringUtils::isNotBlank).collect(Collectors.toList());
                        for (String value : values) {
                            value = value.replaceAll("-", "");
                            if (!postCode.startsWith(value)) {
                                continue first;
                            }
                        }
                    } else if (StaticDict.Regular_ChildType.Five.getValue().equals(childType)) {
                        //订单产品
                        List<String> values = childRegularInfoList.stream().map(PlatformOrderRegularInfoDo::getStartValue).collect(Collectors.toList());
                        //如果有未匹配的平台sku 则不通过
                        Integer childMode = childRegularInfoList.get(0).getChildMode();
                        if (childMode == null) {
                            childMode = 0;
                        }
                        if (0 == childMode) {
                            //全部产品包含在指定产品范围内
                            for (PlatformOrderProductDo productDo : productDos) {
                                if (!values.contains(productDo.getProductId()+"")) {
                                    continue first;
                                }
                            }
                        }
                        else if (1 == childMode) {
                            //全部产品不包含在指定产品范围内
                            for (PlatformOrderProductDo productDo : productDos) {
                                if (values.contains(productDo.getProductId()+"")) {
                                    continue first;
                                }
                            }
                        }
                        else if (2 == childMode) {
                            //任一产品在指定产品范围内
                            boolean flag = false;
                            for (PlatformOrderProductDo productDo : productDos) {
                                if (values.contains(productDo.getProductId()+"")) {
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag) {
                                continue first;
                            }
                        }
                        else if (3 == childMode) {
                            //任一产品不在指定产品范围内
                            boolean flag = false;
                            for (PlatformOrderProductDo productDo : productDos) {
                                if (values.contains(productDo.getProductId()+"")) {
                                    flag = true;
                                    break;
                                }
                            }
                            if (flag) {
                                continue first;
                            }
                        }
                    }
                    //todo 产品数量
                    else if (StaticDict.Regular_ChildType.Five_Qty.getValue().equals(childType)) {
                        Integer childMode = childRegularInfoList.get(0).getChildMode();
                        //产品数量
                        if (0 == childMode) {
                            //总产品数量
                            int sum = productDos.stream().mapToInt(PlatformOrderProductDo::getQty).sum();
                            for (PlatformOrderRegularInfoDo splitInfoDo : childRegularInfoList) {
                                if (splitInfoDo.getStartMatchType() != null && StringUtils.isNotBlank(splitInfoDo.getStartValue())) {
                                    if (splitInfoDo.getStartMatchType() == 5) {
                                        //大于等于
                                        if (sum < Integer.parseInt(splitInfoDo.getStartValue())) {
                                            continue first;
                                        }
                                    }
                                    else if (splitInfoDo.getStartMatchType() == 4) {
                                        if (sum <= Integer.parseInt(splitInfoDo.getStartValue())) {
                                            continue first;
                                        }
                                    }
                                }
                                else if (splitInfoDo.getEndMatchType() != null && StringUtils.isNotBlank(splitInfoDo.getEndValue())) {
                                    if (splitInfoDo.getEndMatchType() == 6) {
                                        //小雨
                                        if (sum >= Integer.parseInt(splitInfoDo.getEndValue())) {
                                            continue first;
                                        }
                                    }
                                    else if (splitInfoDo.getEndMatchType() == 7) {
                                        //小于等于
                                        if (sum > Integer.parseInt(splitInfoDo.getEndValue())) {
                                            continue first;
                                        }
                                    }
                                }
                            }
                        }
                        else if (1 == childMode) {
                            //sku数量
                            Map<Long, Integer> collect = productDos.stream().collect(Collectors.groupingBy(PlatformOrderProductDo::getProductId, Collectors.summingInt(PlatformOrderProductDo::getQty)));
                            Integer startMode = childRegularInfoList.get(childRegularInfoList.size() -1).getStartMatchType();
                            if (8 == startMode) {
                                //并且
                                for (PlatformOrderRegularInfoDo splitInfoDo : childRegularInfoList) {
                                    Long productId = Long.parseLong(splitInfoDo.getStartValue());
                                    if (collect.get(productId) == null) {
                                        continue first;
                                    }
                                    Integer qty = collect.get(productId);
                                    if (splitInfoDo.getEndMatchType() != null && StringUtils.isNotBlank(splitInfoDo.getEndValue())) {
                                        if (splitInfoDo.getEndMatchType() == 1) {
                                            //等于
                                            if (!(qty + "").equals(splitInfoDo.getEndValue())) {
                                                continue first;
                                            }
                                        } else if (splitInfoDo.getEndMatchType() == 4) {
                                            //大于
                                            if (qty <= Integer.parseInt(splitInfoDo.getEndValue())) {
                                                continue first;
                                            }
                                        } else if (splitInfoDo.getEndMatchType() == 6) {
                                            //小于
                                            if (qty >= Integer.parseInt(splitInfoDo.getEndValue())) {
                                                continue first;
                                            }
                                        } else if (splitInfoDo.getEndMatchType() == 7) {
                                            //小于等于
                                            if (qty > Integer.parseInt(splitInfoDo.getEndValue())) {
                                                continue first;
                                            }
                                        } else if (splitInfoDo.getEndMatchType() == 5) {
                                            //大于等于
                                            if (qty < Integer.parseInt(splitInfoDo.getEndValue())) {
                                                continue first;
                                            }
                                        } else if (splitInfoDo.getEndMatchType() == 9) {
                                            //不等于
                                            if ((qty + "").equals(splitInfoDo.getEndValue())) {
                                                continue first;
                                            }
                                        }
                                    }
                                }
                            }
                            else if (10 == startMode) {
                                //或者
                                boolean flag = false;
                                for (PlatformOrderRegularInfoDo splitInfoDo : childRegularInfoList) {
                                    Long productId = Long.parseLong(splitInfoDo.getStartValue());
                                    if (collect.get(productId) == null) {
                                        continue first;
                                    }
                                    Integer qty = collect.get(productId);
                                    if (splitInfoDo.getEndMatchType() != null && StringUtils.isNotBlank(splitInfoDo.getEndValue())) {
                                        if (splitInfoDo.getEndMatchType() == 1) {
                                            //等于
                                            if ((qty+"").equals(splitInfoDo.getEndValue())) {
                                                flag = true;
                                                break;
                                            }
                                        }
                                        else if (splitInfoDo.getEndMatchType() == 4) {
                                            //大于
                                            if (qty > Integer.parseInt(splitInfoDo.getEndValue())) {
                                                flag = true;
                                                break;
                                            }
                                        }
                                        else if (splitInfoDo.getEndMatchType() == 6) {
                                            //小于
                                            if (qty < Integer.parseInt(splitInfoDo.getEndValue())) {
                                                flag = true;
                                                break;
                                            }
                                        }
                                        else if (splitInfoDo.getEndMatchType() == 7) {
                                            //小于等于
                                            if (qty <= Integer.parseInt(splitInfoDo.getEndValue())) {
                                                flag = true;
                                                break;
                                            }
                                        }
                                        else if (splitInfoDo.getEndMatchType() == 5) {
                                            //大于等于
                                            if (qty >= Integer.parseInt(splitInfoDo.getEndValue())) {
                                                flag = true;
                                                break;
                                            }
                                        }
                                        else if (splitInfoDo.getEndMatchType() == 9) {
                                            //不等于
                                            if (!(qty+"").equals(splitInfoDo.getEndValue())) {
                                                flag = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                if (!flag) {
                                    continue first;
                                }
                            }
                        }
                    }
                    else if (StaticDict.Regular_ChildType.Six.getValue().equals(childType)) {
                        //估算重量
                        //获取产品重量
                        List<Long> productIds = productDos.stream().map(PlatformOrderProductDo::getProductId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
                        Map<Long, BigDecimal> weightMap = productService.getProductWeight(productIds, orderDo.getCompanyId()).stream().collect(Collectors.toMap(ProductMsgVo::getId, ProductMsgVo::getWeight));
                        //估算重量
                        BigDecimal weight = new BigDecimal(0);
                        for (PlatformOrderProductDo productDo : productDos) {
                            if (weightMap.get(productDo.getProductId()) == null) {
                                continue;
                            }
                            weight = weight.add(weightMap.get(productDo.getProductId()).multiply(BigDecimal.valueOf(productDo.getQty())));
                        }
                        for (PlatformOrderRegularInfoDo regularInfo : childRegularInfoList) {
                            //判断区间
                            if (StringUtils.isNotBlank(regularInfo.getStartValue()) && regularInfo.getStartMatchType() != null) {
                                //开始
                                double startW = Double.parseDouble(regularInfo.getStartValue());
                                if (regularInfo.getStartMatchType() == 5) {//大于等于
                                    if (weight.doubleValue() < startW) {
                                        continue first;
                                    }
                                } else { // 大于 4
                                    if (weight.doubleValue() <= startW) {
                                        continue first;
                                    }
                                }
                            } else if (StringUtils.isNotBlank(regularInfo.getEndValue()) && regularInfo.getEndMatchType() != null) {
                                double endW = Double.parseDouble(regularInfo.getEndValue());
                                if (regularInfo.getEndMatchType() == 7) {//小于等于
                                    if (weight.doubleValue() > endW) {
                                        continue first;
                                    }
                                } else { // 大于 4
                                    if (weight.doubleValue() >= endW) {// 小于 6
                                        continue first;
                                    }
                                }
                            }
                        }
                    } else if (StaticDict.Regular_ChildType.Seven.getValue().equals(childType)) {
                        //物流跟踪号
                        if (StringUtils.isBlank(orderDo.getTrackNo())) {
                            continue first;
                        }
                        for (PlatformOrderRegularInfoDo regularInfo : childRegularInfoList) {
                            //判断物流跟踪号 是否满足开头 或者包含
                            if (StringUtils.isNotBlank(regularInfo.getStartValue()) && regularInfo.getStartMatchType() != null) {
                                //开头
                                if (!orderDo.getTrackNo().startsWith(regularInfo.getStartValue())) {
                                    continue first;
                                }
                            } else if (StringUtils.isNotBlank(regularInfo.getEndValue()) && regularInfo.getEndMatchType() != null) {
                                //包含
                                if (!orderDo.getTrackNo().contains(regularInfo.getEndValue())) {
                                    continue first;
                                }
                            }
                        }
                    } else if (StaticDict.Regular_ChildType.Eight.getValue().equals(childType) && "mercado".equals(orderDo.getPlatformCode())) {
                        //Mercado 平台承运商
                        List<String> values = childRegularInfoList.stream().map(PlatformOrderRegularInfoDo::getStartValue).collect(Collectors.toList());
                        if (!values.contains(orderDo.getLogisticsCarrier())) {
                            continue first;
                        }
                    } else if (StaticDict.Regular_ChildType.Nine.getValue().equals(childType) && "tiktok".equals(orderDo.getPlatformCode())) {
                        //Tiktok 平台承运商
                        List<String> values = childRegularInfoList.stream().map(PlatformOrderRegularInfoDo::getStartValue).collect(Collectors.toList());
                        if (!values.contains(orderDo.getLogisticsCarrier())) {
                            continue first;
                        }
                    }
                }
                //判断库存够不够
                //仓库id
                List<String> whIds = regularInfoMap.get(regularDo.getId()).stream()
                        .filter(i -> StaticDict.Regular_ModuleType.Zero.getValue().equals(i.getModuleType())
                                && StaticDict.Regular_ChildType.Tenth.getValue().equals(i.getChildType())).map(PlatformOrderRegularInfoDo::getStartValue).collect(Collectors.toList());
                if (whIds.isEmpty()) {
                    continue;
                }
                Long thisWhId = Long.parseLong(whIds.get(0));
                Boolean stockFlag = whStockFlagMap.get(thisWhId);
                if (stockFlag == null) {
                    stockFlag = productStockService.jugSkuStock(skuQtyMap, 0, Long.parseLong(whIds.get(0)), orderDo.getCompanyId());
                    whStockFlagMap.put(thisWhId, stockFlag);
                }
                if (!stockFlag) {
                    continue;
                }
                //以上条件都满足 ok 就是这个规则
                regularId = regularDo.getId();
                reglarName = regularDo.getRegularName();
                break;
            }
            if (regularId == null) {
                //无合适平台订单规则
                whId = -1L;
                channelId = -1L;
            }
            else {
                //仓库id
                List<String> whIds = regularInfoMap.get(regularId).stream()
                        .filter(i -> StaticDict.Regular_ModuleType.Zero.getValue().equals(i.getModuleType())
                                && StaticDict.Regular_ChildType.Tenth.getValue().equals(i.getChildType())).map(PlatformOrderRegularInfoDo::getStartValue).collect(Collectors.toList());
                if (whIds.isEmpty()) {
                    error.append("平台订单规则：").append(reglarName).append("没有设置发货仓库");
                    return error.toString();
                }
                whId = Long.parseLong(whIds.get(0));
                //物流渠道
                List<String> channelIds = regularInfoMap.get(regularId).stream()
                        .filter(i -> StaticDict.Regular_ModuleType.Zero.getValue().equals(i.getModuleType())
                                && StaticDict.Regular_ChildType.Eleventh.getValue().equals(i.getChildType())).map(PlatformOrderRegularInfoDo::getStartValue).collect(Collectors.toList());
                if (channelIds.isEmpty()) {
                    error.append("平台订单规则：").append(reglarName).append("没有设置物流渠道");
                    return error.toString();
                }
                channelId = Long.parseLong(channelIds.get(0));
            }
            //自动审核
//            List<String> autoCheck = regularInfoMap.get(regularId).stream()
//                    .filter(i -> StaticDict.Regular_ModuleType.Zero.getValue().equals(i.getModuleType())
//                            && StaticDict.Regular_ChildType.Zero.getValue().equals(i.getChildType())).map(PlatformOrderRegularInfoDo::getStartValue).collect(Collectors.toList());
        }
        else {
            whId = orderDo.getSendWhId();
            channelId = orderDo.getChannelId();
        }
        boolean qoo10ZhaiFlag = StaticDict.Store_PlatformCode.Qoo10.getValue().equals(orderDo.getPlatformCode()) && skuQtyMap.size() == 1
                && skuQtyMap.values().stream().mapToInt(Integer::intValue).sum() == 2;
        //qoo10订单 同一件商品 买了2件 只能发 黑猫宅急便
        //在判断两个加起来厚度有没有超过3cm 如果没有 还是可以发投涵的
        if (qoo10ZhaiFlag) {
            Map<Long, ProductMinSizeDto> sizeMap = productDao.getProductMinSize(new ArrayList<>(skuQtyMap.keySet())).stream().collect(Collectors.toMap(ProductMinSizeDto::getProductId, i -> i));
            BigDecimal size = new BigDecimal(0);
            for (Long productId : sizeMap.keySet()) {
                size = size.add(sizeMap.get(productId).getMinSize());
            }
            if (size.compareTo(new BigDecimal("1.5")) <= 0) {
                qoo10ZhaiFlag = false;
            }
        }
        if (whId == -1) {
            //获取客户支持的仓库列表
            Map<Integer, List<WarehouseDo>> collect = warehouseService.getWarehouseCompanyDo(orderDo.getCompanyId(), orderDo.getTenantId()).stream().collect(Collectors.groupingBy(WarehouseDo::getWarehouseType));
            List<WarehouseDo> wareDaiLiList = collect.get(1);
            if (wareDaiLiList != null) {
                for (int i = 0; i < wareDaiLiList.size(); i++) {
                    Boolean stockFlag = whStockFlagMap.get(wareDaiLiList.get(i).getId());
                    if (stockFlag == null) {
                        stockFlag = productStockService.jugSkuStock(skuQtyMap, 0, wareDaiLiList.get(i).getId(), orderDo.getCompanyId());
                    }
                    if (!stockFlag) {
                        wareDaiLiList.remove(i);
                        i--;
                    }
                }
                //如果库存不够 且预约单 不是最后一天,预约单等到最后一天
                //判断库存够不够
                if (wareDaiLiList.isEmpty()) {
                    //说明代理仓 无库存
                    if (orderDo.getReserveFlag() == 1 && !DateUtils.dateFormatToString(new Date()).equals(DateUtils.dateFormatToString(orderDo.getReserveEndTime()))) {
                        error.append("代理仓: 库存不足，预约单需等待到最后一天");
//                        this.updatePlatOrderFail(orderDo.getId(), "代理仓: 库存不足，预约单需等待到最后一天", null, null);
                        return error.toString();
                    }
                }
                for (WarehouseDo warehouseDo : wareDaiLiList) {
                    TrialFreightRes freightFee = this.getFreightFee(orderDo, productDos, warehouseDo, channelId);
                    if (freightFee == null) {
                        error.append(warehouseDo.getWhCode()).append(": 报价方案内无合适物流渠道");
                    } else if (!freightFee.isPlaceOrderFlag()) {
                        error.append(warehouseDo.getWhCode()).append(freightFee.getPlaceOrderDetailMsg());
                    }
                    else if (qoo10ZhaiFlag && freightFee.getChannelId() != 3) {
                        error.append(warehouseDo.getWhCode()).append(": qoo10特殊需求,同一件商品买两件只能发黑猫宅急便");
                    }
                    else {
                        //匹配
                        freightResList.add(freightFee);
                    }
                }
            }
            if (freightResList.isEmpty()) {
                //自营仓  这里做了 库存判断，也可以不判断库存，推wms，wms订单会到异常状态(库存不足)
                List<WarehouseDo> wareZiYingList = collect.get(0);
                for (int i = 0; i < wareZiYingList.size(); i++) {
                    Boolean stockFlag = whStockFlagMap.get(wareZiYingList.get(i).getId());
                    if (stockFlag == null) {
                        stockFlag = productStockService.jugSkuStock(skuQtyMap, 0, wareZiYingList.get(i).getId(), orderDo.getCompanyId());
                    }
                    if (!stockFlag) {
                        wareZiYingList.remove(i);
                        i--;
                    }
                }
                if (wareZiYingList.isEmpty()) {
                    //ziying仓 没有合适的
                    error.append("库存不足");
                }
                for (WarehouseDo warehouseDo : wareZiYingList) {
                    TrialFreightRes freightFee = this.getFreightFee(orderDo, productDos, warehouseDo, channelId);
                    if (freightFee == null) {
                        error.append(warehouseDo.getWhCode()).append(": 报价方案内无合适物流渠道");
                    } else if (!freightFee.isPlaceOrderFlag()) {
                        error.append(warehouseDo.getWhCode()).append(",").append(freightFee.getPlaceOrderDetailMsg());
                    }
                    else if (qoo10ZhaiFlag && freightFee.getChannelId() != 3) {
                        error.append(warehouseDo.getWhCode()).append(": qoo10特殊需求,同一件商品买两件只能发黑猫宅急便");
                    }
                    else {
                        //匹配
                        freightResList.add(freightFee);
                    }
                }
            }
        }
        else {
            //指定了仓库
            WarehouseDo warehouseDo = warehouseService.getById(whId);
            if (warehouseDo == null) {
                error.append("平台订单规则 指定仓库不存在");
                return error.toString();
            }
            Boolean stockFlag = whStockFlagMap.get(warehouseDo.getId());
            if (stockFlag == null) {
                stockFlag = productStockService.jugSkuStock(skuQtyMap, 0, warehouseDo.getId(), orderDo.getCompanyId());
            }
            if (!stockFlag) {
                error.append(warehouseDo.getWhCode()).append(": 库存不足");
                //库存不够
//                this.updatePlatOrderFail(orderDo.getId(), warehouseDo.getWhCode()+": 库存不足", null, null);
//                return;
            }
            else {
                TrialFreightRes freightFee = this.getFreightFee(orderDo, productDos, warehouseDo, channelId);
                if (freightFee == null) {
                    error.append(warehouseDo.getWhCode()).append(": 报价方案内无合适物流渠道");
                } else if (!freightFee.isPlaceOrderFlag()) {
                    error.append(warehouseDo.getWhCode()).append(freightFee.getPlaceOrderDetailMsg());
                }
                else if (qoo10ZhaiFlag && freightFee.getChannelId() != 3) {
                    error.append(warehouseDo.getWhCode()).append(": qoo10特殊需求,同一件商品买两件只能发黑猫宅急便");
                }
                else {
                    //匹配
                    freightResList.add(freightFee);
                }
            }
        }
        if (StringUtils.isNotBlank(error.toString()) && StringUtils.isNotBlank(reglarName)) {
            error.append("(").append("平台订单规则：").append(reglarName).append(")");
        }
        return error.toString();
    }

    public TrialFreightRes getFreightFee(PlatformOrderDo orderDo, List<PlatformOrderProductDo> productDos, WarehouseDo warehouseDo, Long channelId) {
        //根据物流渠道 判断是否支持 或者自动获取最便宜的物流渠道
        TrialOmsReq trialOmsReq = new TrialOmsReq();
        trialOmsReq.setCompanyId(orderDo.getCompanyId());
        trialOmsReq.setCountryCode(orderDo.getCountryRegionCode());
        trialOmsReq.setProvinceCode(orderDo.getProvinceCode());
        trialOmsReq.setCityName(orderDo.getCityCode());
        trialOmsReq.setWarehouseId(warehouseDo.getId());
        trialOmsReq.setPostcode(orderDo.getPostcode());
        trialOmsReq.setGoodsType(2);
        //sku
        Map<Long, ProductDo> productIdMatchDo = productService.lambdaQuery()
                .in(ProductDo::getId, productDos.stream().map(PlatformOrderProductDo::getProductId).collect(Collectors.toList()))
                .list().stream().collect(Collectors.toMap(ProductDo::getId, val -> val));
        List<TrialProductReq> trialProductReqs = new ArrayList<>();
        for (PlatformOrderProductDo orderProductDo : productDos) {
            ProductDo productDo = productIdMatchDo.get(orderProductDo.getProductId());
            trialProductReqs.add(new TrialProductReq(orderProductDo.getProductId(), orderProductDo.getSku(), orderProductDo.getQty(), productDo.getCategoryId(),
                    productDo.getHeight(), productDo.getHeightBs(), productDo.getLength(), productDo.getLengthBs(), productDo.getWidth(), productDo.getWidthBs(),
                    productDo.getWeight(), productDo.getWeightBs(), productDo.getWmsHeight(), productDo.getWmsHeightBs(), productDo.getWmsLength(), productDo.getWmsLengthBs(),
                    productDo.getWmsWidth(), productDo.getWmsWidthBs(), productDo.getWmsWeight(), productDo.getWmsWeightBs()));
        }
        trialOmsReq.setProducts(trialProductReqs);
        //选择的物流渠道
        if (channelId == null || channelId == -1) {
            //自动选最便宜的
            trialOmsReq.setAutoChooseCheap(1);
        } else {
            List<LcCodeRes> lcList = new ArrayList<>();
            lcList.add(new LcCodeRes(channelId, "", ""));
            trialOmsReq.setLc(lcList);
        }
        trialOmsReq.setPlatformCode(orderDo.getPlatformCode());
        List<TrialFreightRes> trialFreightRes = quotationSchemeService.omsTrialFreightFee(trialOmsReq);
        if (trialFreightRes.isEmpty()) {
            return null;
        }
        trialFreightRes.get(0).setWarehouseType(warehouseDo.getWarehouseType());
        trialFreightRes.get(0).setWarehouseCode(warehouseDo.getWhCode());
        return trialFreightRes.get(0);
    }

    public void updateAuditCause(List<Long> orderId, boolean mergeFlag, String auditCode, String auditCause) {
        if (orderId == null || orderId.isEmpty()) {
            return;
        }
        if (mergeFlag) {
            auditCause = "合并订单后," + auditCause;
        }
        LambdaUpdateWrapper<PlatformOrderDo> updateWrapper = new LambdaUpdateWrapper<PlatformOrderDo>();
        updateWrapper.set(PlatformOrderDo::getAuditCode, auditCode);
        updateWrapper.set(PlatformOrderDo::getAuditCause, auditCause);
        updateWrapper.set(PlatformOrderDo::getStatus, StaticDict.Platform_Order_Status.Zero.getValue());
        updateWrapper.set(PlatformOrderDo::getSendWhId, null);
        updateWrapper.set(PlatformOrderDo::getChannelId, null);
        updateWrapper.in(PlatformOrderDo::getId, orderId);
        platformOrderService.update(updateWrapper);
    }

//    public void updatePlatOrderFail(Long orderId, String auditCause, Long whId, Long channelId) {
//        LambdaUpdateWrapper<PlatformOrderDo> updateWrapper = new LambdaUpdateWrapper<PlatformOrderDo>();
//        updateWrapper.set(PlatformOrderDo::getAuditCause, auditCause);
//        updateWrapper.set(whId != null, PlatformOrderDo::getSendWhId, whId);
//        updateWrapper.set(channelId != null, PlatformOrderDo::getChannelId, channelId);
//        updateWrapper.eq(PlatformOrderDo::getId, orderId);
//        platformOrderService.update(updateWrapper);
//    }



    public void updatePlatOrderSuccess(List<Long> orderId, Long whId, Long channelId, String carrier, Long userId) {
        if (orderId == null || orderId.isEmpty()) {
            return;
        }
        LambdaUpdateWrapper<PlatformOrderDo> updateWrapper = new LambdaUpdateWrapper<PlatformOrderDo>();
        updateWrapper.set(PlatformOrderDo::getAuditCause, null);
        updateWrapper.set(PlatformOrderDo::getAuditCode, null);
        updateWrapper.set(whId != null, PlatformOrderDo::getSendWhId, whId);
        updateWrapper.set(channelId != null, PlatformOrderDo::getChannelId, channelId);
        updateWrapper.set(PlatformOrderDo::getLogisticsCarrier, carrier);
        updateWrapper.set(PlatformOrderDo::getAuditTime, new Date());
        updateWrapper.in(PlatformOrderDo::getId, orderId);
        updateWrapper.set(PlatformOrderDo::getAuditBy, userId);
        platformOrderService.update(updateWrapper);
    }


    public OrderPackageRes getPackageList(List<PlatformOrderProductDo> itemList) {
        //分包逻辑
        List<List<ProductMemoMsg>> packageList = new ArrayList<>();
        boolean zhaiFlag = false;
        List<Long> productIds = itemList.stream().map(PlatformOrderProductDo::getProductId).collect(Collectors.toList());
        Map<Long, ProductMinSizeDto> sizeMap = new HashMap<>();
        if (!productIds.isEmpty()) {
            sizeMap = productDao.getProductMinSize(productIds).stream().collect(Collectors.toMap(ProductMinSizeDto::getProductId, i->i));
        }
        List<ProductMemoMsg> less30List = new ArrayList<>();
        for (PlatformOrderProductDo item : itemList) {
            ProductMinSizeDto sizeB = sizeMap.get(item.getProductId());
            if (sizeB == null) {
                continue;
            }
            if (sizeB.getMinSize().compareTo(new BigDecimal("3")) > 0) {
                zhaiFlag = true;
                break;
            }
            for (int i = 0; i < item.getQty(); i++) {
                less30List.add(new ProductMemoMsg(item.getSku(), item.getProductId(), sizeB.getLength(), sizeB.getWidth(),
                        sizeB.getHeight(), sizeB.getWeight(), sizeB.getLengthBs(), sizeB.getWidthBs(), sizeB.getHeightBs(), sizeB.getWeightBs(),sizeB.getMinSize()));
            }
        }
        if (!zhaiFlag) {
            this.sort(less30List);
            this.getPackage(packageList, less30List);
        }
        return new OrderPackageRes(packageList, zhaiFlag);
    }


    public void getPackage(List<List<ProductMemoMsg>> packageList, List<ProductMemoMsg> less30List) {
        if (CollUtil.isEmpty(less30List)) {
            return;
        }
        List<ProductMemoMsg> list = new ArrayList<>();
        BigDecimal sizeBig = new BigDecimal(0);
        for (int i = 0; i < less30List.size(); i++) {
            ProductMemoMsg et = less30List.get(i);
            BigDecimal itemMemo = et.getItemMemo();
            if (itemMemo.compareTo(BigDecimal.valueOf(3d)) > 0) {
                packageList.add(Collections.singletonList(et));
                less30List.remove(i);
                i--;
                continue;
            }
            BigDecimal add = sizeBig.add(itemMemo);
            if (add.compareTo(new BigDecimal("3")) > 0) {
                //大于
                break;
            } else {
                sizeBig = add;
                list.add(et);
                less30List.remove(i);
                i--;
            }
        }
        packageList.add(list);
        if (!CollUtil.isEmpty(less30List)) {
            this.getPackage(packageList, less30List);
        }
    }

    public void sort(List<ProductMemoMsg> list) {
        list.sort(
                (o1, o2) -> {
                    if (o1.getItemMemo().compareTo(o2.getItemMemo()) == 0) {
                        return o1.getProductSkuCode().compareTo(o2.getProductSkuCode());
                    } else if (o1.getItemMemo().compareTo(o2.getItemMemo()) > 0) {
                        return -1;
                    } else {
                        return 1;
                    }
                }
        );
    }


    @Override
    public Object testToJinYunApi() throws Exception {
//        Map<String, String> headerMap = new HashMap<>();
//        headerMap.put("content-type", "application/json; charset=utf-8");
////            headerMap.put("token", "C1591:0bb703ea-185a-436a-83b3-57d43856b95a");//C1591:3f82b229-7620-4781-9a06-981eb279cd81
//        headerMap.put("token", "C1591:3f82b229-7620-4781-9a06-981eb279cd81");//C1591:3f82b229-7620-4781-9a06-981eb279cd81
//
////            String serviceUrl = "http://192.168.1.32:8888/api/orderOutput/listPage";
//        String serviceUrl = "https://www.cloudkinto.com/api/product/listPageAll?current=1&pageSize=20&keyword=mskf51ashf&typeOfProduct=&enable=1";
//        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1081);
//        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
//        OkHttpClient.Builder builder = OkHttpUtils.getUnsafeOkHttpClient().newBuilder();
//        builder.connectTimeout(60, TimeUnit.SECONDS)
//                .readTimeout(60, TimeUnit.SECONDS)
//                .writeTimeout(60, TimeUnit.SECONDS)
////                .proxy(proxy)
//                .retryOnConnectionFailure(false);
//        Request.Builder requestBuilder = createSPHeader(headerMap);
//        Request request = requestBuilder.url(serviceUrl).get().build();
//        Response response = null;
//        String body = "";
//        response = builder.build().newCall(request).execute();
//        body = response.body().string();
//        System.out.println("筋斗云返回值：" + body);
//        if (StringUtils.isBlank(body)) {
//            return null;
//        }
//        return JSONObject.parseObject(body);


        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("content-type", "application/json; charset=utf-8");
        String serviceUrl = "http://192.168.1.32:8888/api/open/orderOutput/getTokenLabella?username=donghailongwang";
//        String serviceUrl = "https://www.cloudkinto.com/api/open/orderOutput";

        OkHttpClient client = getUnsafeOkHttpClient();
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 10809);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        OkHttpClient.Builder builder = client.newBuilder();
        builder.connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
//                .proxy(proxy)
                .retryOnConnectionFailure(false);
        Request.Builder requestBuilder = createSPHeader(headerMap);
        Request request = requestBuilder.url(serviceUrl)
                .post(RequestBody.create(MediaType.parse("application/json"), ""))
                .build();
        Response response = null;
        String body = "";
//        response = client.newCall(request).execute();
        response = builder.build().newCall(request).execute();
        body = response.body().string();
        return body;
    }
}
